import { resolve } from 'path'
import { loadEnv } from 'vite'
import { defineConfig, externalizeDepsPlugin } from 'electron-vite'
import vue from '@vitejs/plugin-vue'
import pkgJson from './package.json'
import { createHtmlPlugin } from 'vite-plugin-html'
import { wrapperEnv } from "./scripts/utils";
import analyzer from "rollup-plugin-analyzer";
import { electronSetup, electronSqliteDownload } from './scripts/electron/setup'

export default defineConfig(({ command, mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root)

  const isBuild = command === 'build'
  const { VITE_PORT, VITE_GLOB_APP_TITLE, VITE_SITE_URL, VITE_APP_SHORT_NAME, VITE_DROP_CONSOLE } = wrapperEnv(env);

  return {
    main: {
      build: {
        rollupOptions: {
          input: {
            index: resolve(__dirname, 'electron/main/index.js')
          }
        }
      },
      plugins: [
        {
          ...electronSetup(),
          enforce: 'pre',
        },
        {
          ...electronSqliteDownload(),
          enforce: 'pre',
        },
        externalizeDepsPlugin()
      ]
    },
    preload: {
      build: {
        rollupOptions: {
          input: {
            index: resolve(__dirname, 'electron/preload/index.js')
          }
        }
      },
      plugins: [externalizeDepsPlugin()]
    },
    renderer: {
      root: '.',
      build: {
        publicDir: './public',
        minify: "terser",
        cssCodeSplit: true,
        terserOptions: {
          compress: {
            keep_infinity: true,
            drop_console: VITE_DROP_CONSOLE,
          },
        },
        brotliSize: false,
        chunkSizeWarningLimit: 1500,
        sourcemap: false,
        rollupOptions: {
          input: {
            index: resolve(__dirname, 'index.html')
          },
          output: {
            // 静态资源打包做处理
            chunkFileNames: 'assets/js/[name]-[hash].js',
            entryFileNames: 'assets/js/[name]-[hash].js',
            assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
            manualChunks(id) {
              if (id.includes('node_modules')) {
                return id.toString().split('node_modules/')[1].split('/')[0].toString();
              }
            },
          },
        },
      },
      define: {
        'import.meta.env.ELECTRON': true,
        "import.meta.env.VITE_GLOB_APP_TITLE": JSON.stringify(VITE_GLOB_APP_TITLE),
        "import.meta.env.VITE_APP_SHORT_NAME": JSON.stringify(pkgJson.name),
        "import.meta.env.VITE_APP_VERSION": `"${pkgJson.version}"`
      },
      resolve: {
        alias: {
          '@': resolve('src'),
          moment: "dayjs",
        }
      },
      plugins: [
        vue({
          template: {
            compilerOptions: {
              isCustomElement: tag => /^micro-app/.test(tag)
            }
          }
        }),
        createHtmlPlugin({
          minify: isBuild,
          inject: {
            data: {
              title: VITE_GLOB_APP_TITLE,
              ...(
                isBuild
                ? {
                    siteUrl: VITE_SITE_URL,
                    injectScript: `<script>
                      window.ORGCOMMON_BASE_URL="${VITE_SITE_URL}";
                      window.ORGCOMMON_REPLY_URL="${VITE_SITE_URL}";
                    </script>`,
                }
                : {
                    siteUrl: '',
                    injectScript: '',
                }
              )
            },
          }
        }),
        analyzer({ summaryOnly: true }),
      ],
      esbuild: {
        jsxFactory: "jsx"
      },
      css: {
        preprocessorOptions: {
          less: {
            javascriptEnabled: true,
            charset: false,
            modifyVars: {
              "primary-color": "#2878ff", // 全局主色
            },
            additionalData: '@import "./src/common/styles/base.less";',
          },
        },
      },
      server: {
        port: VITE_PORT,
        cors: true,
        proxy: {
          "/api": {
            target: VITE_SITE_URL,
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, '')
          },
          "/connect": {
            target: VITE_SITE_URL,
            changeOrigin: true,
            // rewrite: (path) => path.replace(/^\/api/, '')
          }
        }
      },
    }
  }
})
